package cn.jiangxiong.pethome.system.fastdfs.controller;

import cn.jiangxiong.pethome.utils.AjaxResult;
import cn.jiangxiong.pethome.utils.FastdfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
@Api(value = "文件上传的API",description="文件上传下载的功能")
public class FastDFSController {
    //上传
    @PostMapping
    //                       请求参数认证    必传             前端请求的参数名叫file
    public AjaxResult upload(@RequestPart(required = true,value = "file")MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            //上传的文件全名包含了后缀名
            String filename = file.getOriginalFilename();
            //获得一个包含了点的文件后缀名
            String suffix = filename.substring(filename.lastIndexOf(".")+1);
            //返回一个上传文件的路径包含组的
            String uploadPath = FastdfsUtil.upload(bytes, suffix);
            return AjaxResult.success().setData(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请联系管理员!!!");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，稍后再试!!!");
        }
    }
    //删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path")String path){
        try {
            //截取路径 截取组
            //处理
            String filePath = path.substring(1);
            //处理路基组group1
            String group = filePath.substring(0, filePath.indexOf("/"));
            //处理路径的截取部分
            String bodyPath = filePath.substring(filePath.indexOf("/") + 1);
            FastdfsUtil.delete(group,bodyPath);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
    //下载
}
